package com.zjb.demo.system.service;

import com.zjb.demo.system.domain.User;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 庄佳彬
 * @since 2023/12/28 18:02
 */
@Component
public class SysPermissionService {

    @Inject
    private SysRoleService roleService;
    @Inject
    private SysMenuService menuService;

    /**
     * 根据用户获取菜单权限
     *
     * @param user 用户对象
     * @return 菜单权限集合
     */
    public Set<String> getMenuPermission(User user) {
        var perms = new HashSet<String>();
        if (user.getId() == 1L) {
            perms.add("*.*.*");
        } else {
            var roles = user.getRoles();
            if (roles != null && !roles.isEmpty()) {
                roles.parallelStream()
                        .forEach(role -> {
                            var rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                            perms.addAll(rolePerms);
                        });
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getId()));
            }
        }

        return perms;
    }

    /**
     * 根据用户获取其角色权限集合
     *
     * @param user 用户对象
     * @return 用户的角色权限集合
     */
    public Set<String> getRolePermission(User user) {
        var result = new HashSet<String>();
        if (user.getId() == 1L) {
            result.add("admin");
        } else {
            result.addAll(roleService.selectRolePermissionByUserId(user.getId()));
        }
        return result;
    }


}
